<template>
  <div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="userInfo.value"
          :name="userInfo.key"
          :label="userInfo.keyName"
          :placeholder="`请输入${userInfo.keyName}`"
          :rules="[{ required: true, message: `请输入${userInfo.keyName}` }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提 交 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { reactive } from 'vue'
import { updateUser } from '@/api/user/user'
import { showFailToast, showSuccessToast } from 'vant'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const userInfo = reactive({
  key: route.query.key as string,
  keyName: route.query.keyName as string,
  value: route.query.value as string,
})
const onSubmit = async () => {
  const params = {
    id: userStore.getCurrentUser().id,
    [userInfo.key]: userInfo.value,
  }
  await updateUser(params).then((res) => {
    const { code, msg } = res
    if (code === 200) {
      showSuccessToast('修改成功')
      router.back()
    } else {
      showFailToast('修改失败')
    }
  })
}
</script>
